#include "xs_def.h"
#include "xs_log.h"
#include "xs_pipe.h"

/* Read characters from the pipe and echo them to @code{stdout}.  */
size_t xs_pipe_io_read (int file, char *messbuff, int len)
{

    FILE *stream;
    int c, t = 0;

    if(messbuff == NULL) return (size_t)EXIT_FAILURE;

    stream = fdopen(file, "r");
    if(stream == NULL){
        xs_logd("fdopen pipe error!");
        return EXIT_FAILURE;
    }

    while((c = fgetc (stream)) != EOF)
    {
        //putchar(c);
        messbuff[t++] = c;
        if(len > t) continue;
        else break; /* Have no enough sapce to store message */
    }

    fclose(stream);
    return t;
}

/* Write some random text to the pipe. */
size_t xs_pipe_io_write (int file, const char *message, size_t len)
{
    FILE *stream;
    size_t t = 0;

    if(message == NULL) return (size_t)EXIT_FAILURE;

    stream = fdopen (file, "w");
    if(stream == NULL){
        xs_logd("fdopen pipe error!");
        return EXIT_FAILURE;
    }
    while(t != len)
        t += fprintf (stream, "%s", message);

    fclose (stream);

    return t;
}

#define CF_END 2
#define CF_CHILD 0
#define CF_PARENT 1
int xs_pipe_test (void)
{
    pid_t pid;
    int xs_pipe[CF_END];
    const char *message = "hello, the world !\n";
    char messbuf[256] = {0};

    /*@group*/
    /* Create the pipe.  */
    if (pipe (xs_pipe))
    {
        fprintf (stderr, "Pipe failed.\n");
        return EXIT_FAILURE;
    }
    /*@end group*/

    /* Create the child process.  */
    pid = fork ();
    if (pid == (pid_t) 0)
    {
        /* This is the child process.
        Close other end first.  */
        close (xs_pipe[CF_PARENT]);
       if ( 0 < xs_pipe_io_read (xs_pipe[CF_CHILD], messbuf, sizeof(messbuf)) )
           xs_logd("%s", messbuf);

        return EXIT_SUCCESS;
    }
    else if (pid < (pid_t) 0)
    {
        /* The fork failed.  */
        fprintf (stderr, "Fork failed.\n");
        return EXIT_FAILURE;
    }
    else
    {
        /* This is the parent process.
        Close other end first.  */
        close (xs_pipe[CF_CHILD]);
        xs_pipe_io_write (xs_pipe[CF_PARENT], message, strlen(message));
        return EXIT_SUCCESS;
    }
}

